package com.x.erp.dao;

import com.x.erp.model.InsuranceOrder;
import com.x.erp.model.InsuranceOrderGoods;
import com.x.framework.dao.BaseDao;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

@Repository
public class InsuranceOrderGoodsDao extends BaseDao {
	/**
	 * 插入多条订单商品信息
	 */
	private final static String insertInsuranceOrderGoodsListSql = "INSERT INTO ERP_INSURANCE_ORDER_GOODS (ORDER_GOODS_ID,ORDER_ID,GOODS_ID,GOODS_NAME,ORDER_GOODS_NUM,ORDER_GOODS_UNIT_PRICE) VALUES ";

	public int insertInsuranceOrderGoodsList(InsuranceOrder insuranceOrder, List<InsuranceOrderGoods> orderGoodsList) throws Exception {
		StringBuilder sql = new StringBuilder(insertInsuranceOrderGoodsListSql);
		List<Object> params = new ArrayList<>();
		if (orderGoodsList == null || orderGoodsList.size() == 0) {
			return 0;
		}
		appendInsertSql(sql, params, insuranceOrder, orderGoodsList);
		return this.execute(sql.toString(), params);
	}

	/**
	 * 查询订单商品列表信息
	 */
	private final static String selectInsuranceOrderGoodsListSql = "SELECT "
			+ "eiog.*, "
			+ "T2.AVAILABLE_NUM "
			+ "FROM ERP_INSURANCE_ORDER_GOODS eiog "
			+ "LEFT JOIN (SELECT T1.ORDER_GOODS_ID,COUNT(1) AS AVAILABLE_NUM FROM ERP_INSURANCE_GOODS_VOUCHER T1 WHERE T1.VOUCHER_VERIFICATION_STATE=0 GROUP BY T1.ORDER_GOODS_ID ) T2 ON T2.ORDER_GOODS_ID=eiog.ORDER_GOODS_ID "
			+ "WHERE 1 = 1 ";

	public List<InsuranceOrderGoods> selectInsuranceOrderGoodsList(InsuranceOrderGoods insuranceOrderGoods) throws Exception {
		StringBuilder sql = new StringBuilder(selectInsuranceOrderGoodsListSql);
		List<Object> params = new ArrayList<>();
		searchCondition(sql, params, insuranceOrderGoods);
		sql.append("ORDER BY eiog.GOODS_ID ");
		return this.queryForList(sql.toString(), InsuranceOrderGoods.class, params);
	}

	/**
	 * 拼接插入语句
	 */
	private void searchCondition(StringBuilder sql, List<Object> params, InsuranceOrderGoods insuranceOrderGoods) {
		if (this.isNotNull(insuranceOrderGoods.getOderGoodsId())) {
			sql.append("AND eiog.ORDER_GOODS_ID = ? ");
			params.add(insuranceOrderGoods.getOderGoodsId());
		}
		if (this.isNotNull(insuranceOrderGoods.getOrderId())) {
			sql.append("AND eiog.ORDER_ID = ? ");
			params.add(insuranceOrderGoods.getOrderId());
		}
		if (this.isNotNull(insuranceOrderGoods.getGoodsId())) {
			sql.append("AND eio.GOODS_ID = ? ");
			params.add(insuranceOrderGoods.getGoodsId());
		}
	}

	/**
	 * 拼接插入条件
	 */
	private void appendInsertSql(StringBuilder sql, List<Object> params, InsuranceOrder insuranceOrder, List<InsuranceOrderGoods> orderGoodsList) {
		for (InsuranceOrderGoods orderGoods : orderGoodsList) {
			sql.append("(?,?,?,?,?,?),");
			params.add(this.getUid(32));
			params.add(insuranceOrder.getOrderId());
			params.add(orderGoods.getGoodsId());
			params.add(orderGoods.getGoodsName());
			params.add(orderGoods.getOrderGoodsNum());
			params.add(orderGoods.getOrderGoodsUnitPrice());
		}
		sql.deleteCharAt(sql.length() - 1);
	}
}
